import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Button, Spin, Typography } from 'antd';
import { BarChartOutlined, DatabaseOutlined, GlobalOutlined, TeamOutlined, CalendarOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { statisticsAPI } from '../utils/api';
import { usePermissions } from '../utils/permissions';
import './StatisticsCard.css';

const { Title } = Typography;

const StatisticsCard = () => {
  const [loading, setLoading] = useState(false);
  const [stats, setStats] = useState({
    total_updates: 0,
    involved_countries: 0,
    involved_companies: 0,
    accessible_codes: 0,
    date_range: {
      earliest_date: null,
      latest_date: null
    }
  });

  const navigate = useNavigate();
  const { isAuthenticated, user } = useAuth(); // 获取 user
  
  // 只有在 user 存在时才创建权限检查器
  const { hasPermission } = usePermissions(user);

  // 延迟权限检查，确保 user 加载完成
  const canViewStatistics = user ? hasPermission('data_statistics') : false;

  useEffect(() => {    
    // 只有在用户已认证且有权限时才获取统计数据
    if (isAuthenticated && user && canViewStatistics) {
      fetchStatistics();
    }
  }, [isAuthenticated, user, canViewStatistics]);

  const fetchStatistics = async () => {
    try {
      setLoading(true);
      const response = await statisticsAPI.getStatisticsOverview();
      setStats(response);
    } catch (error) {
      console.error('获取统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetails = () => {
    navigate('/statistics');
  };

  // 如果用户未认证或没有权限，不显示组件
  if (!isAuthenticated || !user || !canViewStatistics) {
    return null;
  }

  return (
    <div className="statistics-section">
      <div className="statistics-container">
        <div className="statistics-header">
          <h2>数据更新统计</h2>
          <p>昨日至今的数据更新情况概览</p>
        </div>

        <Row gutter={[12, 12]}>
          <Col xs={24} sm={12} lg={4}>
            <Card className="stat-card">
              <Statistic
                title="昨日更新数据"
                value={stats.total_updates}
                prefix={<DatabaseOutlined />}
                valueStyle={{ color: '#1890ff' }}
                loading={loading}
              />
            </Card>
          </Col>

          <Col xs={24} sm={12} lg={4}>
            <Card className="stat-card">
              <Statistic
                title="涉及国家"
                value={stats.involved_countries}
                prefix={<GlobalOutlined />}
                valueStyle={{ color: '#52c41a' }}
                loading={loading}
              />
            </Card>
          </Col>

          <Col xs={24} sm={12} lg={4}>
            <Card className="stat-card">
              <Statistic
                title="涉及公司"
                value={stats.involved_companies}
                prefix={<TeamOutlined />}
                valueStyle={{ color: '#722ed1' }}
                loading={loading}
              />
            </Card>
          </Col>

          <Col xs={24} sm={12} lg={4}>
            <Card className="stat-card">
              <Statistic
                title="可访问编码"
                value={stats.accessible_codes}
                prefix={<BarChartOutlined />}
                valueStyle={{ color: '#fa8c16' }}
                loading={loading}
              />
            </Card>
          </Col>

          {/* 日期范围统计 */}
          <Col xs={24} sm={12} lg={8}>
            <Card className="stat-card">
              <Statistic
                  title="数据日期范围"
                  value={stats.date_range && stats.date_range.earliest_date && stats.date_range.latest_date 
                    ? `${stats.date_range.earliest_date} ~ ${stats.date_range.latest_date}`
                    : '无'
                  }
                  prefix={<CalendarOutlined />}
                  valueStyle={{ 
                    color: '#1890ff'
                  }}
                  loading={loading}
                />
            </Card>
          </Col>
        </Row>

        <div className="statistics-actions">
          <Button
            type="primary"
            size="large"
            icon={<BarChartOutlined />}
            onClick={handleViewDetails}
            loading={loading}
          >
            查看详细统计
          </Button>
        </div>
      </div>
    </div>
  );
};

export default StatisticsCard;